<template>
  <a-drawer
    :width="1200"
    :visible="visible"
    title="快捷录入合同"
    :maskClosable="true"
    @close="closeDrawer"
    :destroyOnClose="true"
    :bodyStyle="{ padding: 0, height: 'calc(100% - 110px)' }"
  >
    <div class="simple-contract">
      <a-steps :current="currentStep" size="small" class="steps">
        <a-step v-for="(item, index) of steps" :key="index" :title="item" />
      </a-steps>

      <div class="content">
        <a-form layout="vertical">
          <div v-show="currentStep == 0">
            <a-row :gutter="8">
              <a-col :span="24">
                <div class="text-title">
                  租客身份信息
                  <a-checkbox style="margin-left: 10px" v-model:checked="formData.owner_info.is_personal">
                    个人
                  </a-checkbox>
                </div>
              </a-col>
              <a-col :span="6">
                <a-form-item
                  :label="formData.owner_info.is_personal ? '租客姓名' : '企业名称'"
                  v-bind="validateInfos['owner_info.owner_name']"
                >
                  <a-input-group>
                    <a-row :gutter="8">
                      <a-col :span="14">
                        <a-input
                          :placeholder="formData.owner_info.is_personal ? '请输入租客姓名' : '请输入企业名称'"
                          v-model:value="formData.owner_info.owner_name"
                        />
                      </a-col>
                      <a-col :span="10">
                        <a-button
                          type="primary"
                          ghost
                          @click="ownerUsersVisible = true"
                        >
                          同住人({{ formData.owner_info.owner_user.length }})
                        </a-button>
                      </a-col>
                    </a-row>
                  </a-input-group>
                </a-form-item>
              </a-col>
              <a-col :span="6" v-if="formData.owner_info.is_personal">
                <a-form-item
                  label="证件号码"
                  v-bind="validateInfos['owner_info.id_card']"
                >
                  <a-input-group>
                    <a-row>
                      <a-col :span="8">
                        <a-select
                          :options="CARD_OPTIONS"
                          v-model:value="formData.owner_info.idcard_type"
                          @select="onCardTypeSelect"
                          style="width: 100%"
                        />
                      </a-col>
                      <a-col :span="16">
                        <a-input
                          :placeholder="ownerPlaceholder"
                          v-model:value="formData.owner_info.id_card"
                        />
                      </a-col>
                    </a-row>
                  </a-input-group>
                </a-form-item>
              </a-col>
              <a-col :span="6" v-if="formData.owner_info.is_personal">
                <a-form-item
                  label="联系号码"
                  v-bind="validateInfos['owner_info.phone']"
                >
                  <a-input
                    placeholder="请输入联系号码"
                    v-model:value="formData.owner_info.phone"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6" v-if="!formData.owner_info.is_personal">
                <a-form-item
                  label="统一社会信用代码"
                  v-bind="validateInfos['owner_info.unifiedSocialCreditCode']"
                >
                  <a-input
                    placeholder="请输入统一社会信用代码"
                    v-model:value="formData.owner_info.unifiedSocialCreditCode"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item
                  label="经办人"
                  v-bind="validateInfos['owner_info.followup_uid']"
                >
                  <a-select
                    :options="initOptions.followup"
                    v-model:value="formData.owner_info.followup_uid"
                    style="width: 100%"
                    placeholder="请选择跟进人"
                  />
                </a-form-item>
              </a-col>
            </a-row>

            <a-row type="flex" justify="space-between" align="middle">
              <a-col>
                <div class="text-title">
                  {{ isLease ? "租赁" : "物业" }}信息
                </div>
              </a-col>
              <a-col>
                <a-select
                  :options="contractTplList"
                  v-model:value="formData.template_id"
                  @select="(val, option) => onContractTplSelect(option)"
                />
              </a-col>
            </a-row>

            <a-row :gutter="8">
              <a-col :span="6">
                <a-form-item
                  label="租赁开始日期"
                  v-bind="validateInfos['rent_info.lease_starttime']"
                >
                  <a-date-picker
                    class="w-100p"
                    v-model:value="formData.rent_info.lease_starttime"
                    :valueFormat="dateFormatStr"
                    :allowClear="false"
                    @change="onLeaseDateChange('start')"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="合同期限">
                  <a-space :size="4">
                    <a-select
                      :options="yearOption"
                      v-model:value="formData.rent_info.expire_data.year"
                      @change="onContactTermChange('year')"
                    />
                    <a-select
                      :options="monthOption"
                      v-model:value="formData.rent_info.expire_data.month"
                      @change="onContactTermChange('month')"
                    />
                    <a-select
                      :options="dayOption"
                      v-model:value="formData.rent_info.expire_data.day"
                      @change="onContactTermChange('day')"
                    />
                    <a-checkable-tag
                      :checked="halfYearChecked"
                      @change="
                        (checked) => onYearTagSelect('halfYear', checked)
                      "
                      class="tag"
                    >
                      半年
                    </a-checkable-tag>
                    <a-checkable-tag
                      :checked="fullYearChecked"
                      @change="
                        (checked) => onYearTagSelect('fullYear', checked)
                      "
                      class="tag"
                    >
                      一年
                    </a-checkable-tag>
                  </a-space>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item
                  label="租赁结束日期"
                  v-bind="validateInfos['rent_info.lease_endtime']"
                >
                  <a-date-picker
                    class="w-100p"
                    v-model:value="formData.rent_info.lease_endtime"
                    :valueFormat="dateFormatStr"
                    :allowClear="false"
                    @change="onLeaseDateChange('end')"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item
                  label="缴费方式（几月一付）"
                  v-bind="validateInfos['rent_info.month_pay']"
                >
                  <a-space>
                    <a-input
                      addon-after="月"
                      v-model:value="formData.rent_info.month_pay"
                      placeholder="请输入"
                      @change="
                        onSeasonPaySelect(formData.rent_info.month_pay == 3)
                      "
                    />
                    <a-checkable-tag
                      :checked="formData.rent_info.season_pay == 1"
                      @change="onSeasonPaySelect"
                      class="tag"
                    >
                      季付
                    </a-checkable-tag>
                  </a-space>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item v-bind="validateInfos['rent_info.contract_price']">
                  <template #label>
                    <span>出房价格</span>
                    <text-tip
                      tips="金额默认含税，如果想额外设置税率，请前往「合同」菜单使用标准合同"
                    />
                  </template>
                  <a-input
                    v-model:value="formData.rent_info.contract_price"
                    placeholder="请输入"
                    @change="onContractPriceChange"
                  >
                    <template #addonAfter>
                      <a-select
                        v-model:value="formData.rent_info.contract_price_unit"
                        :options="initOptions.priceUnit"
                        @select="onContractPriceUnitChange"
                        style="width: 80px"
                      />
                    </template>
                  </a-input>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item
                  label="房屋押金"
                  v-bind="validateInfos['rent_info.bond_price']"
                >
                  <a-space>
                    <a-input
                      addon-after="元"
                      v-model:value="formData.rent_info.bond_price"
                      placeholder="请输入"
                      @change="onBondPaySelect(false)"
                    />
                    <a-checkable-tag
                      :checked="formData.rent_info.bond_pay == 1"
                      @change="onBondPaySelect"
                      class="tag"
                    >
                      押一
                    </a-checkable-tag>
                  </a-space>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item v-bind="validateInfos['rent_info.pay_time']">
                  <template #label>
                    <span>付款时间</span>
                    <a-tooltip
                      v-if="formData.rent_info.payment_time_unit1 == 'unit_3'"
                    >
                      <template #title>
                        账单应收日期固定为当月的指定日期收款
                      </template>
                      <QuestionCircleOutlined
                        style="color: #999; margin-left: 5px"
                      />
                    </a-tooltip>
                  </template>
                  <a-input-group compact>
                    <a-select
                      style="width: 30%"
                      v-model:value="formData.rent_info.payment_time_unit1"
                      :options="initOptions.payTimeUnit1"
                    />
                    <a-input-number
                      placeholder="请输入"
                      v-model:value="formData.rent_info.pay_time"
                      style="width: 30%"
                      :min="0"
                    />
                    <span
                      class="num-input-suffix"
                      v-if="formData.rent_info.payment_time_unit1 == 'unit_3'"
                      >日</span
                    >
                    <a-select
                      style="width: 40%"
                      v-model:value="formData.rent_info.payment_time_unit2"
                      :options="initOptions.payTimeUnit2"
                      v-else
                    />
                  </a-input-group>
                </a-form-item>
              </a-col>
              <a-col
                :span="6"
                v-if="formData.rent_info.payment_time_unit1 == 'unit_3'"
              >
                <a-form-item
                  label="指定日期"
                  v-bind="validateInfos['rent_info.specify_date_unit']"
                >
                  <a-select
                    v-model:value="formData.rent_info.specify_date_unit"
                    :options="initOptions.specify_date_unit"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="赠送天数">
                  <a-input
                    addon-after="天"
                    v-model:value="formData.rent_info.discount_day"
                    placeholder="请输入"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item
                  label="递增约定"
                  v-bind="validateInfos['rent_info.incr_rule']"
                >
                  <a-select
                    v-model:value="formData.rent_info.incr_rule"
                    :options="initOptions.incrFastRule"
                    @select="onIncrRuleSelect"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6" v-if="formData.rent_info.incr_rule == 'incr_2'">
                <a-form-item
                  label="递增值"
                  v-bind="validateInfos['rent_info.incr_num']"
                >
                  <a-input
                    v-model:value="formData.rent_info.incr_num"
                    placeholder="请输入"
                  >
                    <template #addonAfter>
                      <a-select
                        v-model:value="formData.rent_info.incr_unit"
                        :options="initOptions.bond_increment_unit"
                      />
                    </template>
                  </a-input>
                </a-form-item>
              </a-col>
              <a-col :span="6" v-if="formData.rent_info.incr_rule == 'incr_3'">
                <a-form-item
                  label="不规则递增"
                  v-bind="validateInfos['rent_info.incr_list']"
                >
                  <a-button type="primary" ghost @click="onIncrRuleSetting">
                    设置
                  </a-button>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item>
                  <template #label>
                    <span style="margin-right: 6px;">合同所属公司</span>
                    <a-tooltip>
                      <template #title >
                        如果选择了所属公司，则该合同这是以该公司身份签署，不选择则以总公司身份签署。
                      </template >
                      <span><QuestionCircleOutlined /></span>
                    </a-tooltip>
                  </template>
                  <a-select
                    v-model:value="formData.org_branch_id"
                    :fieldNames="{
                      label: 'company',
                      value: 'id',
                    }"
                    :options="companyList"
                    placeholder="请选择"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <div class="text-title">租客其他押金信息</div>
              </a-col>
              <a-col :span="24">
                <a-row :gutter="[12, 12]">
                  <a-col
                    :span="12"
                    v-for="(item, index) of formData.bond_info"
                    :key="index"
                  >
                    <a-card size="small" :bodyStyle="{ background: '#f7f7f7' }">
                      <a-row :gutter="8" align="middle">
                        <a-col :span="10">
                          <a-form-item label="费用类型">
                            <a-select
                              placeholder="请选择"
                              v-model:value="item.bond_type"
                              :options="initOptions.bondCostType"
                              :disabled="item.is_template"
                            />
                          </a-form-item>
                        </a-col>
                        <a-col :span="10">
                          <a-form-item label="押金金额">
                            <a-input
                              placeholder="请输入"
                              v-model:value="item.bond_price"
                              addon-after="元"
                            />
                          </a-form-item>
                        </a-col>
                        <a-col
                          :span="4"
                          class="text-right"
                          v-if="!item.is_template"
                        >
                          <a-button
                            type="link"
                            danger
                            @click="onBondInfoRemove(index)"
                          >
                            <DeleteOutlined />
                          </a-button>
                        </a-col>
                      </a-row>
                    </a-card>
                  </a-col>
                  <a-col :span="24" v-bind="validateInfos.bond_info">
                    <a-button type="primary" ghost @click="onBondInfoAdd">
                      <template #icon>
                        <PlusOutlined />
                      </template>
                      添加租客其他押金
                    </a-button>
                  </a-col>
                </a-row>
              </a-col>
            </a-row>

            <a-row :gutter="8" class="mt-20">
              <a-col :span="24">
                <div class="text-title">租客其他付费信息</div>
              </a-col>
              <a-col
                :span="8"
                v-for="(item, index) of formData.other_info"
                :key="index"
                style="margin-bottom: 10px"
              >
                <a-card size="small" :bodyStyle="{ background: '#f7f7f7' }">
                  <a-row :gutter="8" align="middle">
                    <a-col :span="20">
                      <a-form-item>
                        <template #label>
                          <span>{{ getCostTypeTxt(item.cost_type) }}</span>
                        </template>
                        <a-input-group compact>
                          <a-select
                            style="width: 40%"
                            v-model:value="item.other_rule"
                            :options="initOptions.otherOwnerCostRule"
                          />
                          <a-input
                            style="width: 60%"
                            v-model:value="item.price"
                            placeholder="请输入"
                            :addon-after="
                              item.other_rule == 'rule_3' ? '元' : '元/月'
                            "
                          />
                        </a-input-group>
                      </a-form-item>
                    </a-col>
                    <a-col
                      :span="4"
                      class="text-right"
                      v-if="!item.is_template"
                    >
                      <a-button
                        type="link"
                        danger
                        @click="onOtherInfoRemove(index)"
                      >
                        <DeleteOutlined />
                      </a-button>
                    </a-col>
                  </a-row>
                </a-card>
              </a-col>
              <a-col :span="24">
                <a-button type="primary" ghost @click="onOtherInfoAdd">
                  <template #icon>
                    <PlusOutlined />
                  </template>
                  添加租客其他付费信息
                </a-button>
              </a-col>
            </a-row>


            <a-row :gutter="8" class="mt-20">
              <a-col :span="24" style="margin-bottom: 6px">
                <a-row type="flex" justify="space-between" align="middle">
                  <a-col>
                    <div class="text-title">
                      拓展字段
                    </div>
                  </a-col>
                  <a-col>
                    <a-button type="primary" ghost @click="extraManageVisible = true">
                      字段管理
                    </a-button>
                  </a-col>
                </a-row>
              </a-col>
              <a-card class="w-100p" size="small" :bordered="false" :bodyStyle="{padding: '0 4px'}">
                <template v-if="formData?.extra_field?.length">
                  <a-row :gutter="12" :wrap="true">
                    <a-col
                      :span="6"
                      v-for="(extraItem, index) in formData.extra_field"
                      :key="index"
                    >
                      <a-form-item :label="extraItem.name">
                        <a-input
                          placeholder="请输入"
                          v-model:value="extraItem.value"
                        />
                      </a-form-item>
                    </a-col>
                  </a-row>
                </template>
              </a-card>
            </a-row>

            <a-row :gutter="8" class="mt-20">
              <a-col :span="24">
                <div class="text-title">备注信息</div>
              </a-col>
              <a-col :span="24">
                <a-textarea
                  placeholder="请输入备注内容"
                  v-model:value="formData.remark"
                  :auto-size="{ minRows: 4 }"
                />
              </a-col>
            </a-row>
          </div>

          <div v-show="currentStep == 1">
            <a-row :gutter="[0, 12]">
              <a-col :span="24">
                <div class="text-title">租客身份证照片</div>
                <div class="card-content">
                  <a-popover
                    placement="bottom"
                    v-for="(item, index) in cardImg"
                    :key="index"
                    :visible="item.visible"
                    @visibleChange="
                      (show) => {
                        if (
                          !formData.owner_info.idcard_img[item.key] ||
                          !show
                        ) {
                          item.visible = show;
                        }
                      }
                    "
                  >
                    <template #content>
                      <PhotoUpload
                        @request="$utils.commonRequest"
                        :staticPathes="$utils.staticPathes"
                        :imgAction="$utils.imgAction"
                        :token="$store.getters.token"
                        accept="image/jpg,image/jpeg,image/gif,image/png"
                        @successPhoto="
                          (url) => {
                            successPhoto(url, item.key);
                          }
                        "
                      />
                    </template>
                    <div
                      v-if="!formData.owner_info.idcard_img[item.key]"
                      class="card-box"
                    >
                      <div class="card-upload">
                        <img :src="`${item.src}`" />
                        <span class="font-gary">{{ item.title }}</span>
                      </div>
                    </div>
                    <div v-else class="card-img">
                      <img
                        class="img"
                        :src="formData.owner_info.idcard_img[item.key]"
                      />
                      <div class="mask">
                        <a-space>
                          <a
                            :href="formData.owner_info.idcard_img[item.key]"
                            target="_blank"
                          >
                            <EyeOutlined class="icon"
                          /></a>
                          <DeleteOutlined
                            class="icon"
                            @click="
                              () => {
                                formData.owner_info.idcard_img[item.key] = '';
                              }
                            "
                          />
                        </a-space>
                      </div>
                    </div>
                  </a-popover>
                </div>
              </a-col>
              <a-col :span="24">
                <div class="text-title">纸质出房合同照片（电子合同可不传）</div>
                <a-upload
                  :file-list="contractPhotos"
                  name="file"
                  list-type="picture-card"
                  class="avatar-uploader"
                  accept="image/jpg,image/jpeg,image/gif,image/png"
                  :headers="{ 'org-token': $store.getters.token }"
                  :show-upload-list="true"
                  :action="$utils.fileAction"
                  :data="{ dir: 'new_contract_contract_photo' }"
                  :multiple="true"
                  @change="(info) => onPhotoUpload(info, 'contractPhotos')"
                >
                  <div style="color: rgba(0, 0, 0, 0.5)">
                    <plus-outlined />
                    <div>上传</div>
                  </div>
                </a-upload>
                <div class="tips">图片仅支持png、jpg、gif格式</div>
              </a-col>
              <a-col :span="24">
                <AttachmentInfo
                  :params="attachParams"
                  typeFrom="contract"
                  @getObjectId="getObjectId"
                />
              </a-col>
            </a-row>
          </div>

          <div v-show="currentStep == 2">
            <a-row :gutter="[8, 12]">
              <a-col :span="24">
                <a-form-item label=" ">
                  <a-radio-group v-model:value="formData.attach_type">
                    <a-radio-button :value="1">纸质合同</a-radio-button>
                    <a-radio-button :value="2">电子合同</a-radio-button>
                  </a-radio-group>
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <a-form-item label="选择模板">
                  <a-space>
                    <a-select
                      :options="printTemplateList"
                      v-model:value="formData.apply_template_id"
                      @select="onPrintTemplateSelect"
                      placeholder="请选择模板"
                      style="width: 300px"
                    />
                    <a-button
                      :disabled="!formData.apply_template_id"
                      @click="onPrintTemplateGet"
                    >
                      生成
                    </a-button>
                  </a-space>
                </a-form-item>
              </a-col>
              <a-col
                :span="24"
                v-if="formData.apply_contract && formData.apply_contract.result"
              >
                <a-card hoverable style="width: 300px" size="small">
                  <template class="ant-card-actions" #actions>
                    <a-button type="text" @click="onContractTextDownload">
                      下载
                    </a-button>
                    <a-button type="text" @click="onContractTextRemove">
                      删除
                    </a-button>
                  </template>
                  <a-card-meta
                    :title="currentPrintTemplate.label || '纸质合同文本'"
                    :description="formData.apply_contract.contractName"
                  >
                    <template #avatar>
                      <a-avatar :size="48" style="background-color: #2681f3">
                        <template #icon>
                          <cu-icon type="org-hetongwenben" />
                        </template>
                      </a-avatar>
                    </template>
                  </a-card-meta>
                </a-card>
              </a-col>
            </a-row>
          </div>

          <div v-show="currentStep == 3">
            <Result
              status="success"
              title="合同创建成功"
              :sub-title="approve_status_txt"
              v-if="
                originContract.contract_status != 13 &&
                (!originContract.approve_status ||
                  originContract.approve_status == 1 ||
                  originContract.approve_status == 2)
              "
            >
              <template #extra>
                <a-button
                  type="primary"
                  @click="goApproval"
                  v-if="originContract.approve_id"
                >
                  查看审批
                </a-button>
                <a-button @click="goDetail" v-if="originContract.contract_id">
                  查看详情
                </a-button>
              </template>
            </Result>
            <Result
              status="error"
              :title="originContract.contract_status_txt || '审批未通过'"
              v-else
            >
              <template #extra>
                <a-button
                  type="primary"
                  @click="goEdit"
                  v-if="originContract.contract_id"
                >
                  重新编辑
                </a-button>
                <a-button @click="goApproval" v-if="originContract.approve_id">
                  查看审批
                </a-button>
              </template>
            </Result>
          </div>
        </a-form>
      </div>
    </div>
    <div class="drawer-footer">
      <a-row type="flex" justify="space-between" align="middle">
        <a-col>
          <a-button @click="closeDrawer"> 关闭 </a-button>
        </a-col>
        <a-col>
          <a-space>
            <a-button
              v-show="currentStep > 0 && currentStep < 3"
              @click="lastStep"
            >
              上一步
            </a-button>
            <a-button
              type="primary"
              v-show="currentStep < 2"
              @click="nextStep"
              :loading="nextStepLoading"
            >
              下一步
            </a-button>
            <a-button
              type="primary"
              v-show="currentStep == 2"
              @click="submit"
              :loading="submitLoading"
            >
              提交
            </a-button>
          </a-space>
        </a-col>
      </a-row>
    </div>

    <OwnerUsers
      :visible="ownerUsersVisible"
      :list="formData.owner_info.owner_user"
      @cancel="ownerUsersVisible = false"
      @success="onOwnerUsersManage"
    />

    <OtherInfoAdd
      :visible="otherInfoVisible"
      @cancel="otherInfoVisible = false"
      @success="onOtherInfoAddSuccess"
    />

    <a-modal
      v-model:visible="incrRuleVisible"
      title="不规则递增"
      centered
      width="800px"
      @ok="onIncrRuleSuccess"
      cancelText="关闭"
      okText="确认"
    >
      <a-table
        :columns="incrRuleCol"
        :pagination="false"
        rowKey="sort"
        size="small"
        bordered
        :dataSource="formData.rent_info.incr_list"
      >
        <template #bodyCell="{ text, record, index, column }">
          <template v-if="column.key === 'incr_price'">
            <span>{{ text }}元/月</span>
          </template>
          <template v-if="column.key === 'incr_num'">
            <a-space>
              <a-radio-group
                v-model:value="record.incr_unit"
                :disabled="record.sort == 1"
                @change="onIncrRuleChange('unit', record)"
              >
                <a-radio-button value="unit1"> 百分比 </a-radio-button>
                <a-radio-button value="unit2"> 金额 </a-radio-button>
              </a-radio-group>
              <a-input
                style="width: 120px"
                placeholder="请输入"
                v-model:value="record.incr_num"
                :disabled="record.sort == 1"
                :addon-after="record.incr_unit == 'unit1' ? '%' : '元'"
                @change="onIncrRuleChange('num', record)"
              />
            </a-space>
          </template>
        </template>
      </a-table>
    </a-modal>

    <!--  拓展字段管理   -->
    <ExtraManage :visible="extraManageVisible" @closeModal="closeExtraManage" />
  </a-drawer>
</template>

<script>
import {
  defineComponent,
  reactive,
  toRefs,
  watch,
  computed,
  nextTick,
  toRaw,
  ref,
  createVNode,
} from "vue";
import request from "../../../common/utils/request";
import { Form, message, Result, Modal } from "ant-design-vue";
import utils from "../../../common/utils/utils";
import moment from "moment";
import OwnerUsers from "./modules/OwnerUsers.vue";
import OtherInfoAdd from "./modules/OtherInfoAdd.vue";
import AttachmentInfo from "../AttachmentInfo/index.vue";
import { TextTip } from "bl-common-vue3";
import {
  PlusOutlined,
  DeleteOutlined,
  QuestionCircleOutlined,
  EyeOutlined,
  SyncOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons-vue";
import store from "../../../store";
import { useRouter } from "vue-router";
import { CARD_OPTIONS } from "@/common/utils/constant";
import { PhotoUpload } from "bl-common-vue3";
import _ from "lodash";
import ExtraManage from "@/views/contract/NewContract/modules/ExtraManage.vue";

const useForm = Form.useForm;

export default defineComponent({
  name: "NewSimpleContract",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    roomDetail: {
      type: Object,
      default: () => ({}),
    },
    id: {
      type: Number,
      default: 0,
    },
    contractInfo: {
      type: Object,
      default: () => ({}),
    },
  },
  components: {
    ExtraManage,
    PhotoUpload,
    EyeOutlined,
    OwnerUsers,
    TextTip,
    PlusOutlined,
    DeleteOutlined,
    OtherInfoAdd,
    AttachmentInfo,
    Result,
    QuestionCircleOutlined,
    SyncOutlined,
  },
  setup(props, { emit }) {
    const ROUTER = useRouter();

    const DATE_FORMAT = "YYYY-MM-DD";

    const TODAY = moment();

    const REQUIRE_RULE = [{ required: true, message: "必填项" }];

    const PHONE_RULE = [
      {
        required: true,
        validator: (rules, value) => utils.phoneValidator(rules, value),
      },
    ];

    const INCRRULE_RULE = [
      {
        required: true,
        validator: async (rules, value) => {
          if (!value.length) {
            return Promise.reject("请设置不规则递增规则");
          }
          for (let item of value) {
            if (item.sort > 1 && !item.incr_num) {
              return Promise.reject("请填写每一项规则的递增标准");
            }
          }
          return Promise.resolve();
        },
      },
    ];

    const dayAfterYear = (year, startDate, subtractDay = true) => {
      const date = startDate ? moment(startDate) : moment();
      return subtractDay
        ? date.add(year, "years").subtract(1, "days")
        : date.add(year, "years");
    };

    const dayAfterMonth = (month, startDate) => {
      const date = startDate ? moment(startDate) : moment();
      return date.add(month, "months").subtract(1, "days");
    };

    const dayAfterDays = (days, startDate) => {
      const date = startDate ? moment(startDate) : moment();
      return date.add(days, "days");
    };

    const initState = {
      currentStep: 0,
      nextStepLoading: false,
      submitLoading: false,

      originContract: {},
      contractDetail: {},

      ownerPlaceholder: "请输入身份证号",
      ownerUsersVisible: false,

      contractTplList: [],
      currentContractTpl: {},
      defaultClause: {},

      halfYearChecked: false,
      fullYearChecked: true,
      yearDiffer: 0,

      incrRuleVisible: false,
      contractUnitPrice: 0,

      otherInfoVisible: false,

      ownerPhotos: [],
      contractPhotos: [],

      attachParams: {},

      printTemplateList: [],
      currentPrintTemplate: {},

      checkedBuild: {},
      roomInfo: {},

      reportDetailParams: [],
      reportDetail: [],
    };

    const state = reactive({
      steps: STEPS,
      initOptions: {},
      CARD_OPTIONS,
      dateFormatStr: DATE_FORMAT,
      yearOption: [],
      monthOption: [],
      dayOption: [],
      incrRuleCol: INCR_RULE,
      companyList: [],

      ...initState,

      formData: {
        owner_info: {
          owner_name: "",
          is_personal: true,
          unifiedSocialCreditCode: '', // 企业租客时营业执照
          owner_user: [],
          id_card: "",
          idcard_type: "idcard",
          phone: "",
          followup_uid: undefined,
          followup_uname: "",
          idcard_img: {
            front_url: "",
            back_url: "",
            hand_url: "",
          },
        },
        template_id: undefined,
        rent_info: {
          sign_time: TODAY,
          lease_starttime: TODAY,
          expire_data: { year: 1, month: 0, day: 0 },
          lease_endtime: dayAfterYear(1),
          month_pay: 1,
          season_pay: 0,
          contract_price: "",
          contract_price_unit: "unit_3",
          bond_price: "",
          bond_pay: 1,
          payment_time_unit1: "unit_1",
          pay_time: "",
          payment_time_unit2: "unit_2",
          specify_date_unit: "unit1",
          discount_day: "",
          incr_rule: "incr_1",
          incr_num: "",
          incr_unit: "unit2",
          incr_list: [],
        },
        bond_info: [],
        other_info: [],
        remark: "",

        owner_photo: [],
        contract_photo: [],
        object_id: "",

        attach_type: 1,
        apply_template_id: undefined,
        apply_contract: null,

        contract_number: "",
        // 自定义字段
        extra_field: [],
        org_branch_id: undefined,
      },
      rulesData: {
        "owner_info.owner_name": REQUIRE_RULE,
        "owner_info.id_card": REQUIRE_RULE,
        "owner_info.phone": PHONE_RULE,
        "owner_info.followup_uid": REQUIRE_RULE,
        "rent_info.lease_starttime": REQUIRE_RULE,
        "rent_info.lease_endtime": REQUIRE_RULE,
        "rent_info.contract_price": REQUIRE_RULE,
        "rent_info.bond_price": REQUIRE_RULE,
        "rent_info.pay_time": REQUIRE_RULE,
        "rent_info.specify_date_unit": REQUIRE_RULE,
        "rent_info.incr_rule": REQUIRE_RULE,
      },
      cardImg: [
        {
          src: utils.staticPath + "images/contract/renxiang.png",
          title: "上传身份证人像面",
          key: "front_url",
        },
        {
          src: utils.staticPath + "images/contract/guohui.png",
          title: "上传身份证国徽面",
          key: "back_url",
        },
        {
          src: utils.staticPath + "images/contract/shouchi.png",
          title: "上传手持身份证照",
          key: "hand_url",
        },
      ],

      reportList: [],
      extraManageVisible: false,
    });

    const { resetFields, validate, validateInfos } = useForm(
      state.formData,
      state.rulesData
    );

    const isLease = computed(
      () =>
        state.currentContractTpl.attribute &&
        state.currentContractTpl.attribute.includes("lease")
    );

    const submit = () => {
      state.submitLoading = true;
      const {
        roomInfo,
        checkedBuild,
        currentContractTpl,
        formData,
        ownerPhotos,
        contractPhotos,
        attachParams,
      } = state;
      let params = {
        village_id: roomInfo.extra.village_id,
        build_id: roomInfo.extra.build_id,
        room_id: roomInfo.id,
        build_bind: checkedBuild,
        template_id: currentContractTpl.id,
        scene: currentContractTpl.scene,
        owner_info: {...formData.owner_info, is_personal: state.formData.owner_info.is_personal ? 1 : 0},
        rent_info: formData.rent_info,
        bond_info:
          formData.bond_info && formData.bond_info.length
            ? formData.bond_info.filter(
                (item) => !!item.bond_price && !item.is_template
              )
            : [],
        other_info: formData.other_info,
        owner_photo: ownerPhotos.map((file) => file.url),
        contract_photo: contractPhotos.map((file) => file.url),
        attach_type: formData.attach_type,
        apply_template_id: formData.apply_template_id,
        apply_contract: formData.apply_contract,
        remark: formData.remark,
        object_id: attachParams.objectId,
        sign_time: moment(formData.rent_info.sign_time).format(DATE_FORMAT),
        lease_starttime: moment(formData.rent_info.lease_starttime).format(
          DATE_FORMAT
        ),
        lease_endtime: moment(formData.rent_info.lease_endtime).format(
          DATE_FORMAT
        ),
        expense_clause: getExpenseClause(),
        contract_number: formData.contract_number,
        extra_field: formData.extra_field,
        org_branch_id: formData.org_branch_id,
      };
      console.log("paramsparamsparamsparamsparams", params);
      request
        .post("/org", "/contract/fastCreate", params)
        .then((res) => {
          if (res.contractData) {
            state.originContract = res.contractData;
          }
          state.currentStep++;
        })
        .finally(() => {
          state.submitLoading = false;
        });
    };

    const nextStep = () => {
      state.nextStepLoading = true;
      console.log("formData", toRaw(state.formData));

      if (state.currentStep == 0) {
        validate()
          .then(() => {
            if (!state.formData.owner_info.is_personal && !state.formData.owner_info.owner_user.length) {
              message.warning("同住人至少填写一个");
              state.nextStepLoading = false;
              return;
            }
            if (state.formData.owner_info.is_personal) {
              // 个人
              state.formData.owner_info.unifiedSocialCreditCode = '';
            } else {
              // 企业
              state.formData.owner_info.id_card = '';
              state.formData.owner_info.phone = '';
            }
            getReportDetails().then(() => {
              state.currentStep++;
              state.nextStepLoading = false;
            });
          })
          .catch(() => {
            state.nextStepLoading = false;
          });
      } else {
        if (state.currentStep == 1) {
          getPrintTemplate();
        }
        state.currentStep++;
        state.nextStepLoading = false;
      }
    };

    const lastStep = () => {
      state.currentStep--;
    };

    const onContractTextDownload = () => {
      window.open(state.formData.apply_contract.result.fileUrl);
    };

    const onContractTextRemove = () => {
      state.formData.apply_contract = null;
    };

    const onPrintTemplateGet = () => {
      const { formData, checkedBuild, roomInfo } = state;
      if (formData.apply_contract) {
        formData.apply_contract = null;
      }
      let params = {
        template_id: state.currentPrintTemplate.id,
        contractData: {
          followup_uid: formData.owner_info.followup_uid,
          lease_square: [{ ...roomInfo }],
          sign_time: moment(formData.rent_info.sign_time).format(DATE_FORMAT),
          lease_starttime: moment(formData.rent_info.lease_starttime).format(
            DATE_FORMAT
          ),
          lease_endtime: moment(formData.rent_info.lease_endtime).format(
            DATE_FORMAT
          ),
          build_bind: checkedBuild,
          owner_info: formData.owner_info,
          late_fee: {},
          tax_clause: {
            taxRule: 2,
            taxRate: 0,
          },
          expense_clause: getExpenseClause(),
          contract_number: formData.contract_number,
          extra_field: formData.extra_field,
          org_branch_id: formData.org_branch_id,
        },
      };
      request.post("/org", "/create/printContract", params).then((res) => {
        state.formData.apply_contract = res;
      });
    };

    const getExpenseClause = () => {
      const {
        defaultClause,
        roomInfo,
        reportDetailParams,
        formData,
        reportDetail,
        checkedBuild,
        currentContractTpl,
      } = state;
      const { multiple_clause } = currentContractTpl;
      // 如果当前合同模板下设置了多个条款，需要多次
      if (state.reportList && state.reportList.length > 1) {
        let result = [];
        state.reportList.forEach((item, index) => {
          result.push({
            clause_id: item.id,
            clause_type: item.clause_type,
            attribute: item.attribute,
            basic_clause: {
              lease_area: roomInfo.lease_area,
              lease_square: "squareMetre",
              lease_mode: "",
            },
            bond_clause:
              item.attribute == "lease"
                ? reportDetailParams[index].bondTerms
                : {},
            tax_clause: {
              taxRule: 2,
              taxRate: 0,
            },
            remark_clause: formData.remark,
            discount_clause: reportDetailParams[index].discountTerms,
            increment_clause: reportDetailParams[index].incrTerms,
            multiple_clause: reportDetailParams[index].leaseTerms,
            report_detail: reportDetail[index],
            checked_build: checkedBuild,
          });
        });
        return result;
      } else {
        return [
          {
            clause_id: defaultClause.id,
            clause_type: defaultClause.clause_type,
            attribute: defaultClause.attribute,
            basic_clause: {
              lease_area: roomInfo.lease_area,
              lease_square: "squareMetre",
              lease_mode: "",
            },
            bond_clause: reportDetailParams[0].bondTerms,
            tax_clause: {
              taxRule: 2,
              taxRate: 0,
            },
            remark_clause: formData.remark,
            discount_clause: reportDetailParams[0].discountTerms,
            increment_clause: reportDetailParams[0].incrTerms,
            multiple_clause: reportDetailParams[0].leaseTerms,
            report_detail: reportDetail[0],
            checked_build: checkedBuild,
          },
        ];
      }
    };

    const onPrintTemplateSelect = (value, option) => {
      state.currentPrintTemplate = option;
    };

    const getPrintTemplate = () => {
      request
        .post("/org", "/contract/printTemplate", {
          buildIds: [props.roomDetail.build_id],
        })
        .then((res) => {
          state.printTemplateList = res.list.map((item) => ({
            value: item.id,
            label: item.template_name,
            ...item,
          }));
        });
    };

    const getObjectId = (id) => {
      state.attachParams.objectId = id;
    };

    const onPhotoUpload = (info, type) => {
      console.log("info: ", info.fileList);
      let result = [];
      info.fileList.forEach((file) => {
        if (file && file.status == "done" && file.response) {
          const { code, data, msg } = file.response;
          if (code == 1000) {
            file.url = data.fileUrl;
            result.push(file);
          } else {
            message.warning(msg);
          }
        } else {
          result.push(file);
        }
      });
      state[type] = result;
    };

    const getReportDetails = () => {
      return new Promise((resolve, reject) => {
        const { defaultClause, formData, roomInfo } = state;
        // 如果当前合同模板下设置了多个条款，需要多次生成账单明细
        const { multiple_clause } = state.currentContractTpl;
        if (multiple_clause && multiple_clause.length > 1) {
          console.log("formData.other_info", formData.other_info);
          // 如果其他付费信息是模板中的副条款，特殊判断处理
          // 如果付费信息随房租支付：生成账单，不加入other_info
          // 如果付费信息不支付：不加到other_info中，也不生成账单
          // 如果付费信息一次性支付：加到other_info，不生成账单

          // 所有模板副条款id
          let subClauseIds = [];
          multiple_clause.forEach((item) => {
            if (item.id != state.defaultClause.id) {
              subClauseIds.push(item.id);
            }
          });
          console.log("subClauseIds", subClauseIds);

          //最终需要塞到主条款中的otherInfo
          let resultOtherInfo = [];
          //最终需要生成账单的副条款id
          let resultReportSubIds = [];

          formData.other_info.forEach((otherItem) => {
            if (otherItem.is_template == 1) {
              if (otherItem.other_rule == "rule_1") {
                // 随房租支付 ==> 生成账单
                // if (otherItemotherItem.price && Number(otherItem.price) > 0) {
                //   resultReportSubIds.push(otherItem.id);
                // }
                resultReportSubIds.push(otherItem.id);
              } else if (otherItem.other_rule == "rule_3") {
                // 一次性支付 ==> 加到other_info
                resultOtherInfo.push(otherItem);
              }
            } else {
              resultOtherInfo.push(otherItem);
            }
          });

          console.log("resultReportSubIds", resultReportSubIds);
          console.log("resultOtherInfo", resultOtherInfo);

          state.reportList = multiple_clause.filter(
            (item) =>
              resultReportSubIds.includes(item.id) ||
              item.id == state.defaultClause.id
          );
          state.reportList.forEach((item, index) => {
            let params = {
              clause_id: item.id,
              lease_area: roomInfo.lease_area,
              lease_square: "squareMetre",
              sign_time: moment(formData.rent_info.sign_time).format(
                DATE_FORMAT
              ),
              lease_starttime: moment(
                formData.rent_info.lease_starttime
              ).format(DATE_FORMAT),
              lease_endtime: moment(formData.rent_info.lease_endtime).format(
                DATE_FORMAT
              ),
              unit_price_point: 2,
              calculate_accuracy: "accuracy_1",
              calculate_order: "order_1",
              receivable_round: 0,
              leaseTerms: [
                {
                  compute_lease: "unit1",
                  // contract_unit_price: formData.rent_info.contract_price,
                  contract_price_unit: formData.rent_info.contract_price_unit,
                  payment_time_unit1: formData.rent_info.payment_time_unit1,
                  payment_time: formData.rent_info.pay_time,
                  payment_time_unit2: formData.rent_info.payment_time_unit2,
                  charge_type: "unit2",
                  year_days: 365,
                  payCycle: formData.rent_info.month_pay,
                  lease_divide: "unit1",
                  divide_rate: "",
                  convert_day_price: "convert_1",
                  charge_begintime: moment(
                    formData.rent_info.lease_starttime
                  ).format(DATE_FORMAT),
                  charge_endtime: moment(
                    formData.rent_info.lease_endtime
                  ).format(DATE_FORMAT),
                },
              ],
              bondTerms: {},
              rentTaxTerms: {
                taxRule: 2,
                taxRate: 0,
              },
              incrTerms: [],
              discountTerms: [],
              fastTerms: {
                rent_info: { ...formData.rent_info },
                bond_info:
                  formData.bond_info && formData.bond_info.length
                    ? formData.bond_info.filter(
                        (item) => !!item.bond_price && !item.is_template
                      )
                    : [],
                other_info: [],
              },
            };
            if (formData.rent_info.discount_day) {
              params.discountTerms.push({
                discount_type: "select_1",
                exempt_lease_type: "select_1",
                remark: "",
                discount_start_time: formData.rent_info.lease_starttime,
                discount_end_time: dayAfterDays(
                  formData.rent_info.discount_day,
                  formData.rent_info.lease_starttime
                ),
              });
            }
            if (formData.rent_info.incr_rule == "incr_2") {
              const incrList = getIncrList();
              console.log("incrList: ", incrList);
              console.log("incr_num: ", formData.rent_info.incr_num);
              params.incrTerms = incrList.map((item) => {
                return {
                  incrDate: item.incr_date,
                  incrPrice: formData.rent_info.incr_num,
                  incrPriceUnit: formData.rent_info.incr_unit,
                  incrBond: 0,
                  incrBondUnit: "unit2",
                };
              });
              params.incrTerms.splice(0, 1);
            } else if (formData.rent_info.incr_rule == "incr_3") {
              params.incrTerms = formData.rent_info.incr_list.map((item) => {
                return {
                  incrDate: item.incr_date,
                  incrPrice:
                    item.incr_unit == "unit1" ? item.incr_num : item.incr_price,
                  incrPriceUnit: item.incr_unit,
                  incrBond: 0,
                  incrBondUnit: "unit2",
                };
              });
              params.incrTerms.splice(0, 1);
            }

            // 只有主条款有
            if (item.id == state.defaultClause.id) {
              params.bondTerms = {
                bond_type: isLease.value ? "bond_2" : "bond_3",
                bond_unit: "unit_2",
                bond_price: formData.rent_info.bond_price,
                currencyUnit: "CNY",
                bond_type_txt: getCostTypeTxt(
                  isLease.value ? "bond_2" : "bond_3"
                ),
                bond_unit_txt: "元",
                currency: "人民币",
              };
              params.fastTerms.other_info = [...resultOtherInfo];
              params.fastTerms.rent_info.contract_price =
                formData.rent_info.contract_price;
              params.leaseTerms[0].contract_unit_price =
                formData.rent_info.contract_price;
            } else {
              formData.other_info.forEach((other) => {
                if (other.id == item.id) {
                  params.fastTerms.rent_info.contract_price = other.price;
                  params.leaseTerms[0].contract_unit_price = other.price;
                }
              });
              formData.bond_info.forEach((bond) => {
                if (bond.is_template && bond.clauseId == item.id) {
                  params.bondTerms = {
                    bond_type: bond.bond_type,
                    bond_unit: "unit_2",
                    bond_price: bond.bond_price,
                    currencyUnit: "CNY",
                    bond_type_txt: getCostTypeTxt(bond.bond_type),
                    bond_unit_txt: "元",
                    currency: "人民币",
                  };
                }
              });
            }

            state.reportDetailParams[index] = params;

            request
              .post("/org", "/contract/reportPays", {
                baseTerm: params,
              })
              .then((res) => {
                state.reportDetail[index] = res.data;
                if (index + 1 == state.reportList.length) {
                  resolve();
                }
              });
          });
        } else {
          let params = {
            clause_id: defaultClause.id,
            lease_area: roomInfo.lease_area,
            lease_square: "squareMetre",
            sign_time: moment(formData.rent_info.sign_time).format(DATE_FORMAT),
            lease_starttime: moment(formData.rent_info.lease_starttime).format(
              DATE_FORMAT
            ),
            lease_endtime: moment(formData.rent_info.lease_endtime).format(
              DATE_FORMAT
            ),
            unit_price_point: 2,
            calculate_accuracy: "accuracy_1",
            calculate_order: "order_1",
            receivable_round: 0,
            leaseTerms: [
              {
                compute_lease: "unit1",
                contract_unit_price: formData.rent_info.contract_price,
                contract_price_unit: formData.rent_info.contract_price_unit,
                payment_time_unit1: formData.rent_info.payment_time_unit1,
                payment_time: formData.rent_info.pay_time,
                payment_time_unit2: formData.rent_info.payment_time_unit2,
                charge_type: "unit2",
                year_days: 365,
                payCycle: formData.rent_info.month_pay,
                lease_divide: "unit1",
                divide_rate: "",
                convert_day_price: "convert_1",
                charge_begintime: moment(
                  formData.rent_info.lease_starttime
                ).format(DATE_FORMAT),
                charge_endtime: moment(formData.rent_info.lease_endtime).format(
                  DATE_FORMAT
                ),
              },
            ],
            bondTerms: {
              bond_type: isLease.value ? "bond_2" : "bond_3",
              bond_unit: "unit_2",
              bond_price: formData.rent_info.bond_price,
              currencyUnit: "CNY",
              bond_type_txt: getCostTypeTxt(
                isLease.value ? "bond_2" : "bond_3"
              ),
              bond_unit_txt: "元",
              currency: "人民币",
            },
            rentTaxTerms: {
              taxRule: 2,
              taxRate: 0,
            },
            incrTerms: [],
            discountTerms: [],
            fastTerms: {
              rent_info: { ...formData.rent_info },
              bond_info:
                formData.bond_info && formData.bond_info.length
                  ? formData.bond_info.filter((item) => !!item.bond_price)
                  : [],
              other_info: [...formData.other_info],
            },
          };
          if (formData.rent_info.discount_day) {
            params.discountTerms.push({
              discount_type: "select_1",
              exempt_lease_type: "select_1",
              remark: "",
              discount_start_time: formData.rent_info.lease_starttime,
              discount_end_time: dayAfterDays(
                formData.rent_info.discount_day,
                formData.rent_info.lease_starttime
              ),
            });
          }
          if (formData.rent_info.incr_rule == "incr_2") {
            const incrList = getIncrList();
            console.log("incrList: ", incrList);
            console.log("incr_num: ", formData.rent_info.incr_num);
            params.incrTerms = incrList.map((item) => {
              return {
                incrDate: item.incr_date,
                incrPrice: formData.rent_info.incr_num,
                incrPriceUnit: formData.rent_info.incr_unit,
                incrBond: 0,
                incrBondUnit: "unit2",
              };
            });
            params.incrTerms.splice(0, 1);
          } else if (formData.rent_info.incr_rule == "incr_3") {
            params.incrTerms = formData.rent_info.incr_list.map((item) => {
              return {
                incrDate: item.incr_date,
                incrPrice:
                  item.incr_unit == "unit1" ? item.incr_num : item.incr_price,
                incrPriceUnit: item.incr_unit,
                incrBond: 0,
                incrBondUnit: "unit2",
              };
            });
            params.incrTerms.splice(0, 1);
          }
          state.reportDetailParams[0] = params;
          request
            .post("/org", "/contract/reportPays", {
              baseTerm: params,
            })
            .then((res) => {
              state.reportDetail[0] = res.data;
              resolve();
            });
        }
      });
    };

    const onOtherInfoAddSuccess = (info) => {
      const { checked } = info;
      checked.forEach((item) => {
        state.formData.other_info.push({
          id: item.id,
          cost_type: item,
          price: "",
          other_rule: "rule_1",
        });
      });
      state.otherInfoVisible = false;
    };

    const onOtherInfoAdd = () => {
      state.otherInfoVisible = true;
    };

    const onOtherInfoRemove = (index) => {
      state.formData.other_info.splice(index, 1);
    };

    const getCostTypeTxt = (costType) => {
      if (state.initOptions.allCostType) {
        const costTypeItem = state.initOptions.allCostType.find(
          (it) => it.value == costType
        );
        return costTypeItem.label;
      }
      return "";
    };

    const onBondInfoAdd = () => {
      state.formData.bond_info.push({
        bond_type: undefined,
        bond_price: "",
      });
    };

    const onBondInfoRemove = (index) => {
      state.formData.bond_info.splice(index, 1);
    };

    const onIncrRuleSuccess = () => {
      state.incrRuleVisible = false;
    };

    const onIncrRuleChange = (type, current) => {
      if (current.incr_num) {
        if (current.incr_unit == "unit1") {
          current.incr_price = (
            Number(state.contractUnitPrice) *
            Number(current.incr_num) *
            0.01
          ).toFixed(2);
        } else {
          current.incr_price = Number(current.incr_num).toFixed(2);
        }
      } else {
        current.incr_price = 0;
      }
    };

    const onIncrRuleSelect = () => {
      const { rent_info } = state.formData;
      if ("incr_1" == rent_info.incr_rule) {
        delete state.rulesData["rent_info.incr_num"];
        delete state.rulesData["rent_info.incr_list"];
        state.formData.rent_info.incr_list = [];
        state.formData.rent_info.incr_num = "";
      } else {
        const start = moment(rent_info.lease_starttime);
        const end = moment(rent_info.lease_endtime).add(1, "days");
        let _differYear = end.diff(start, "years", true);
        if (Math.ceil(state.yearDiffer) !== Math.ceil(_differYear)) {
          state.formData.rent_info.incr_list = [];
        }
        state.yearDiffer = _differYear;
        if (state.yearDiffer <= 1) {
          message.warning("合同起止时间未超过1年，无法设置递增！");
          nextTick(() => {
            rent_info.incr_rule = "incr_1";
            onIncrRuleSelect();
          });
        } else {
          if ("incr_2" == rent_info.incr_rule) {
            state.rulesData["rent_info.incr_num"] = REQUIRE_RULE;
          }
          if ("incr_3" == rent_info.incr_rule) {
            state.rulesData["rent_info.incr_list"] = INCRRULE_RULE;
          }
        }
      }
    };

    const onIncrRuleSetting = () => {
      if (!state.formData.rent_info.contract_price) {
        message.warning("请先填写出房价格！");
        return;
      }
      if (!state.formData.rent_info.incr_list.length) {
        state.formData.rent_info.incr_list = getIncrList();
      }
      getIncrPrice();
      state.incrRuleVisible = true;
    };

    const getIncrList = () => {
      let result = [];
      for (let i = 1; i <= Math.ceil(state.yearDiffer); i++) {
        result.push({
          sort: i,
          incr_date:
            i == 1
              ?  moment(state.formData.rent_info.lease_starttime).format(
                DATE_FORMAT
              )
              : dayAfterYear(
                  i - 1,
                  state.formData.rent_info.lease_starttime,
                  false
                ).format(
                DATE_FORMAT
              ),
          incr_num: i == 1 ? 0 : "",
          incr_unit: "unit1",
          incr_price: 0,
        });
      }
      return result;
    };

    const getIncrPrice = () => {
      if (state.formData.rent_info.incr_list.length) {
        state.formData.rent_info.incr_list.forEach((item) => {
          if (item.incr_num) {
            if (item.incr_unit == "unit1") {
              item.incr_price = (
                Number(state.contractUnitPrice) *
                Number(item.incr_num) *
                0.01
              ).toFixed(2);
            } else {
              item.incr_price = Number(item.incr_num).toFixed(2);
            }
          } else {
            item.incr_price = 0;
          }
        });
      }
    };

    const onContractPriceUnitChange = (value) => {
      if ("unit_2" == value && !props.roomDetail.rental_area) {
        message.warning("该房间没有录入面积，不能选择按面积计费！");
        nextTick(() => {
          state.formData.rent_info.contract_price_unit = "unit_3";
        });
        return;
      }
      getBondPrice(true);
    };

    let bondTimeout = null;
    const onContractPriceChange = () => {
      if (bondTimeout) {
        clearTimeout(bondTimeout);
        bondTimeout = null;
      }
      bondTimeout = setTimeout(() => {
        getBondPrice(true);
      }, 800);
    };

    const getBondPrice = (getUnitPrice = false) => {
      const { rent_info } = state.formData;
      if (getUnitPrice) {
        if (rent_info.contract_price) {
          if (rent_info.contract_price_unit == "unit_2") {
            let area = Number(props.roomDetail.rental_area);
            if (!isLease.value && props.roomDetail.charging_area) {
              area = Number(props.roomDetail.charging_area);
            }
            state.contractUnitPrice = (
              Number(rent_info.contract_price) * area
            ).toFixed(2);
          } else {
            state.contractUnitPrice = rent_info.contract_price;
          }
        } else {
          state.contractUnitPrice = 0;
        }
        getIncrPrice();
      }
      if (rent_info.bond_pay == 1) {
        rent_info.bond_price = state.contractUnitPrice;
      }
    };

    const onOwnerUsersManage = (info) => {
      state.formData.owner_info.owner_user = info.list;
      state.ownerUsersVisible = false;
    };

    const onBondPaySelect = (checked) => {
      state.formData.rent_info.bond_pay = checked ? 1 : 0;
      if (checked) {
        getBondPrice();
      }
    };

    const onSeasonPaySelect = (checked) => {
      state.formData.rent_info.season_pay = checked ? 1 : 0;
      if (checked && state.formData.rent_info.month_pay != 3) {
        state.formData.rent_info.month_pay = 3;
      }
    };

    const onLeaseDateChange = (type) => {
      if (type == "start") {
        onContactTermChange();
      } else {
        const { rent_info } = state.formData;
        if (
          moment(rent_info.lease_starttime).isAfter(rent_info.lease_endtime)
        ) {
          message.warning("结束时间不能早于开始时间");
          onContactTermChange();
        } else {
          state.fullYearChecked = false;
          state.halfYearChecked = false;
          onIncrRuleSelect();
        }
      }
    };

    const onContactTermChange = (type) => {
      const { rent_info } = state.formData;
      state.fullYearChecked = false;
      state.halfYearChecked = false;
      if (
        rent_info.expire_data.year == 1 &&
        rent_info.expire_data.month == 0 &&
        rent_info.expire_data.day == 0
      ) {
        state.fullYearChecked = true;
      } else if (
        rent_info.expire_data.year == 0 &&
        rent_info.expire_data.month == 6 &&
        rent_info.expire_data.day == 0
      ) {
        state.halfYearChecked = true;
      }
      let monthCount = parseInt(
        rent_info.expire_data.year * 12 + Number(rent_info.expire_data.month)
      );
      rent_info.lease_endtime = dayAfterMonth(
        monthCount,
        rent_info.lease_starttime
      );
      if (rent_info.expire_data.day) {
        rent_info.lease_endtime = dayAfterDays(
          rent_info.expire_data.day,
          rent_info.lease_endtime
        );
      }
      onIncrRuleSelect();
    };

    const onYearTagSelect = (type, checked) => {
      if (checked) {
        if (type == "halfYear") {
          state.formData.rent_info.expire_data.month = 6;
          state.formData.rent_info.expire_data.year = 0;
        } else {
          state.formData.rent_info.expire_data.year = 1;
          state.formData.rent_info.expire_data.month = 0;
        }
        state.formData.rent_info.expire_data.day = 0;
        onContactTermChange();
      } else {
        state[`${type}Checked`] = checked;
      }
    };

    watch(
      () => state.formData.owner_info.followup_uid,
      (val) => {
        if (val) {
          const currentUser = state.initOptions.followup.find(
            (it) => it.value == val
          );
          if (currentUser) {
            state.formData.owner_info.followup_uname = currentUser.label;
          } else {
            state.formData.owner_info.followup_uid = undefined;
          }
        }
      }
    );

    watch(() => state.formData.owner_info.is_personal, (val) => {
      if (val) {
        // 个人租客
        state.rulesData["owner_info.id_card"] = REQUIRE_RULE;
        state.rulesData["owner_info.phone"] = PHONE_RULE;
        delete state.rulesData["owner_info.unifiedSocialCreditCode"];
      } else {
        // 企业租客
        delete state.rulesData["owner_info.id_card"];
        delete state.rulesData["owner_info.phone"];
        state.rulesData["owner_info.unifiedSocialCreditCode"] = REQUIRE_RULE;
      }
    })

    const onCardTypeSelect = (value, option) => {
      state.ownerPlaceholder = `请输入${option.label}`;
    };

    // 生成默认的保证金信息
    const getDefaultBondInfo = () => {
      let list = state.currentContractTpl.multiple_clause;
      if (list && list.length) {
        state.defaultClause = list.find((item) =>
          isLease.value
            ? item.attribute == "lease"
            : item.attribute == "property"
        );
        list = list.filter((item) =>
          isLease.value
            ? item.attribute != "lease"
            : item.attribute != "property"
        );
        state.formData.bond_info = [];
        list.forEach((clause) => {
          if (
            clause.id !== state.defaultClause.id &&
            clause?.tempClauseInfo?.bond_clause?.bond_price &&
            Number(clause.tempClauseInfo.bond_clause.bond_price) > 0
          ) {
            let price = "";
            let bondInfo = clause.tempClauseInfo.bond_clause;
            let normalInfo = clause.tempClauseInfo.normalClause;
            if (bondInfo.bond_unit == "unit_2") {
              price = bondInfo.bond_price;
            } else {
              // unit_2表示月，要换算成元
              if (
                normalInfo.length > 0 &&
                normalInfo[0].month_price_arr &&
                normalInfo[0].month_price_arr.month_lease_price &&
                Number(normalInfo[0].month_price_arr.month_lease_price) > 0
              ) {
                price =
                  bondInfo.bond_price *
                  Number(normalInfo[0].month_price_arr.month_lease_price);
              }
            }
            state.formData.bond_info.push({
              clauseId: clause.id,
              bond_type: bondInfo.bond_type,
              bond_price: price,
              is_template: 1, //is_template = 1 表示是模板中的副条款
            });
          }
        });
      }
    };

    const getDefaultOtherInfo = () => {
      let list = state.currentContractTpl.multiple_clause;
      if (list && list.length) {
        state.defaultClause = list.find((item) =>
          isLease.value
            ? item.attribute == "lease"
            : item.attribute == "property"
        );
        list = list.filter((item) =>
          isLease.value
            ? item.attribute != "lease"
            : item.attribute != "property"
        );
        state.formData.other_info = list.map((clause) => {
          let price = "";
          // 如果模板中设置了价格，默认填充，
          if (
            clause.tempClauseInfo &&
            clause.tempClauseInfo.normalClause &&
            clause.tempClauseInfo.normalClause.length > 0 &&
            clause.tempClauseInfo.normalClause[0].month_price_arr
          ) {
            let month_price_arr =
              clause.tempClauseInfo.normalClause[0].month_price_arr;
            if (
              month_price_arr.month_lease_price &&
              Number(month_price_arr.month_lease_price) > 0
            ) {
              price = month_price_arr.month_lease_price;
            }
          }
          return {
            id: clause.id,
            cost_type: clause.cost_type,
            price: price,
            other_rule: "rule_1",
            is_template: 1, //is_template = 1 表示是模板中的副条款
          };
        });
      }
      // 如果模板中主条款设置了租金价格，默认填充
      if (
        state.defaultClause.tempClauseInfo &&
        state.defaultClause.tempClauseInfo.normalClause &&
        state.defaultClause.tempClauseInfo.normalClause.length > 0 &&
        state.defaultClause.tempClauseInfo.normalClause[0].month_price_arr
      ) {
        let month_price_arr =
          state.defaultClause.tempClauseInfo.normalClause[0].month_price_arr;
        if (
          month_price_arr.month_lease_price &&
          Number(month_price_arr.month_lease_price) > 0
        ) {
          state.formData.rent_info.contract_price =
            month_price_arr.month_lease_price;
          onContractPriceChange();
        }
      }
    };

    // 请求合同编号
    const getContractNumber = () => {
      request
        .get("/org", "/create/contract-no", {
          template_scene: state.currentContractTpl.scene,
          template_id: state.currentContractTpl.id,
          lease_starttime: moment(state.formData.rent_info.lease_starttime).format(
            DATE_FORMAT
          ),
        })
        .then((res) => {
          state.formData.contract_number = res.no;
        });
    };

    const onContractTplSelect = (option) => {
      console.log(option);
      state.currentContractTpl = option;
      getDefaultOtherInfo();
      getDefaultBondInfo();
      state.roomInfo.lease_area =
        !isLease.value && state.roomInfo.charging_area
          ? state.roomInfo.charging_area
          : state.roomInfo.rental_area;

      getContractNumber();
    };

    const getContractTpl = () => {
      request
        .get("/org", "/contract/fastClauseTemplate", {
          build_id: props.roomDetail.build_id,
          room_id: props.roomDetail.id,
        })
        .then((res) => {
          state.contractTplList = res.list.map((item) => ({
            label: item.template_name,
            value: item.id,
            ...item,
          }));
          if (state.formData.template_id) {
            state.currentContractTpl = state.contractTplList.find(
              (it) => it.value == state.formData.template_id
            );
            if (
              state.currentContractTpl &&
              state.currentContractTpl.multiple_clause &&
              state.currentContractTpl.multiple_clause.length
            ) {
              state.defaultClause =
                state.currentContractTpl.multiple_clause.find((item) =>
                  isLease.value
                    ? item.attribute == "lease"
                    : item.attribute == "property"
                );
            }
          } else {
            state.formData.template_id = state.contractTplList[0].value;
            onContractTplSelect(state.contractTplList[0]);
          }
        });
    };

    const setDetail = () => {
      const { formData, contractDetail } = state;
      formData.template_id = contractDetail.template_id;
      formData.owner_info = contractDetail.owner_info;
      formData.owner_info.is_personal = !!contractDetail?.owner_info?.is_personal == 1;
      formData.rent_info = contractDetail.rent_info;
      formData.bond_info = contractDetail.bond_info || [];
      formData.other_info = contractDetail.other_info || [];
      state.checkedBuild = contractDetail.build_bind;
      state.roomInfo = contractDetail.build_bind.room[0];
      formData.remark = contractDetail.remark || "";
      formData.attach_type = contractDetail.attach_type;
      formData.apply_template_id = contractDetail.apply_template_id;
      formData.apply_contract = contractDetail.apply_contract;
      formData.extra_field = contractDetail?.extra_field || [];
      if (contractDetail.owner_photo) {
        state.ownerPhotos = contractDetail.owner_photo.map((url, index) => ({
          uid: `owner_photo_${index}`,
          name: `租客身份证照片_${index}`,
          status: "done",
          url,
        }));
      }
      if (contractDetail.contract_photo) {
        state.contractPhotos = contractDetail.contract_photo.map(
          (url, index) => ({
            uid: `contract_photo_${index}`,
            name: `纸质出房合同照片照片_${index}`,
            status: "done",
            url,
          })
        );
      }
      const start = moment(contractDetail.rent_info.lease_starttime);
      const end = moment(contractDetail.rent_info.lease_endtime).add(1, "days");
      state.yearDiffer = end.diff(start, "years", true);
    };

    const getContractDetail = () => {
      request
        .get("/org", "/contract/fastDetail", {
          id: props.id,
        })
        .then((res) => {
          state.contractDetail = res.easyContract;
          getContractTpl();
          nextTick(() => {
            setDetail();
          });
        });
    };

    const getBuildBind = () => {
      const { roomDetail } = props;

      state.roomInfo = {
        id: roomDetail.id,
        room_number: roomDetail.room_number,
        room_name: roomDetail.room_name,
        room_name_txt: roomDetail.room_name_txt,
        layer_id: roomDetail.layer_id,
        layer_name: roomDetail.layer_name,
        lease_square: "squareMetre",
        rent_area: roomDetail.rent_area,
        rental_area: roomDetail.rental_area,
        charging_area: roomDetail.charging_area,
        build_id: roomDetail.build_id,
        village_id: roomDetail.village_id,
        extra: roomDetail.extra || {
          village_id: roomDetail.village_id,
          village_name: roomDetail.village_name,
          build_id: roomDetail.build_id,
          build_name: roomDetail.build_name,
          layer_id: roomDetail.layer_id,
          layer_name: roomDetail.layer_name,
        },
      };

      state.checkedBuild = {
        village: {
          id: state.roomInfo.extra.village_id,
          name: state.roomInfo.extra.village_name,
        },
        build: [
          {
            id: state.roomInfo.extra.build_id,
            build_name: state.roomInfo.extra.build_name,
          },
        ],
        room: [state.roomInfo],
      };
    };

    const getInitData = () => {
      request.get("/org", "/contract/fastInit").then((res) => {
        const result = transfromInitData(res.initData);
        state.initOptions = {
          ...state.initOptions,
          ...result,
        };
        state.initOptions.priceUnit = state.initOptions.priceUnit.filter(
          (item) => ["unit_2", "unit_3"].includes(item.value)
        );
        console.log("state.initOptions", state.initOptions);
      });
      request.get("/org", "/user/getAdminList").then((res) => {
        state.initOptions.followup = res.list.map((item) => ({
          label: item.realname,
          value: item.uid,
        }));
        if (store.getters.userInfo.uid) {
          state.formData.owner_info.followup_uid = store.getters.userInfo.uid;
        }
      });
      if (!state.yearOption.length) {
        for (let i = 0; i <= 30; i++) {
          if (i <= 5) {
            state.yearOption.push({ value: i, label: `${i}年` });
          }
          if (i <= 12) {
            state.monthOption.push({ value: i, label: `${i}月` });
          }
          state.dayOption.push({ value: i, label: `${i}天` });
        }
      }
    };
    const transfromInitData = (data) => {
      let result = {};
      for (let key in data) {
        result[key] = data[key].map((item) => ({
          label: item.name,
          value: item.key,
        }));
      }
      return result;
    };

    const successPhoto = (data, key) => {
      const { url } = data;
      state.formData.owner_info.idcard_img[key] = url;
    };

    const getBuildBindByRoomInfo = (roomInfo) => {
      return {
        village: {
          id: roomInfo.extra.village_id,
          name: roomInfo.extra.village_name,
          short_name: roomInfo.extra.village_short_name,
        },
        build: {
          id: roomInfo.extra.build_id,
          build_name: roomInfo.extra.build_name,
          build_number: roomInfo.extra.build_number,
        },
        room: [
          {
            id: roomInfo.id,
            build_id: roomInfo.extra.build_id,
            layer_id: roomInfo.extra.layer_id,
            room_name: roomInfo.room_name,
            layer_name: roomInfo.extra.layer_name,
            room_number: roomInfo.room_number,
            layer_number: roomInfo.extra.layer_number,
          },
        ],
      };
    };

    const getExtraField = () => {
      return new Promise((resolve, reject) => {
        request.get("/org", "/org/contract/extra/field/show").then((res) => {
          state.formData.extra_field = (res?.list || []).map((v) => {
            return {
              name: v,
              value: "",
            };
          });
          resolve();
        });
      });
    };

    const closeExtraManage = () => {
      let lastArr = _.cloneDeep(state.formData.extra_field);
      getExtraField().then(() => {
        state.formData.extra_field.map((v) => {
          let data = lastArr?.find((item) => item.name === v.name);
          if (data) {
            v.value = data?.value || "";
          }
        });
      });
      state.extraManageVisible = false;
    };

    const getCompanyList = () => {
      request.post("/org", "/company/getDefaultBranchId", {}).then( async (data) => {
        let company_id = data?.org_branch_id;
        await request.get("/org", "/company/orgAndBranch", {}).then((res) => {
          state.companyList = res?.list || [];
          let defaultId = (res?.list || []).find((v) => v.id == company_id)?.id;
          if (defaultId) {
            state.formData.org_branch_id = defaultId;
          } else {
            let systemId = (res?.list || []).find((v) => v.is_system == 1)?.id;
            state.formData.org_branch_id = systemId;
          }
        });
      })
    };

    const init = () => {
      if (
        props.id &&
        props.contractInfo.approve_id &&
        props.contractInfo.contract_id
      ) {
        state.currentStep = 3;
        state.originContract = {
          ...props.contractInfo,
        };
      } else {
        getInitData();
        getBuildBind();
        getContractTpl();
        getExtraField();
        getCompanyList();
      }
    };

    const reset = () => {
      resetFields();
      for (let key in initState) {
        state[key] = initState[key];
      }
    };

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          init();
        } else {
          reset();
        }
      }
    );

    const closeDrawer = () => {
      emit("closeDrawer");
    };

    const goEdit = () => {
      state.currentStep = 0;
      getInitData();
      getContractDetail();
    };

    const goApproval = () => {
      closeDrawer();
      ROUTER.push({
        name: "contractApproval",
        query: {
          approveId: state.originContract.approve_id,
          contractId: state.originContract.contract_id,
        },
      });
    };

    const goDetail = () => {
      closeDrawer();
      ROUTER.push({
        name: "contractDetail",
        query: {
          id: state.originContract.contract_id,
        },
      });
    };

    return {
      isLease,
      ...toRefs(state),
      validateInfos,
      closeDrawer,
      lastStep,
      nextStep,
      submit,
      onCardTypeSelect,
      onContractTplSelect,
      onYearTagSelect,
      onSeasonPaySelect,
      onBondPaySelect,
      onOwnerUsersManage,
      onContactTermChange,
      onLeaseDateChange,
      onContractPriceChange,
      onContractPriceUnitChange,
      onIncrRuleSelect,
      onIncrRuleSuccess,
      onIncrRuleSetting,
      onIncrRuleChange,
      onBondInfoAdd,
      onBondInfoRemove,
      getCostTypeTxt,
      onOtherInfoAdd,
      onOtherInfoAddSuccess,
      onOtherInfoRemove,
      onPhotoUpload,
      getObjectId,
      onPrintTemplateGet,
      onPrintTemplateSelect,
      onContractTextRemove,
      onContractTextDownload,
      goApproval,
      goDetail,
      goEdit,
      successPhoto,
      closeExtraManage,
    };
  },
});

const STEPS = ["登记租客信息", "上传证件照", "签署合同", "录入完成"];
const INCR_RULE = [
  {
    dataIndex: "sort",
    title: "递增顺序",
  },
  {
    dataIndex: "incr_date",
    title: "递增时间",
  },
  {
    dataIndex: "incr_price",
    key: "incr_price",
    title: "递增金额",
  },
  {
    dataIndex: "incr_num",
    key: "incr_num",
    title: "递增标准",
  },
];
</script>

<style lang="less" scoped>
.simple-contract {
  width: 100%;
  height: 100%;
  overflow: hidden auto;
  padding: 10px;

  :deep(.ant-select:not(.ant-select-customize-input) .ant-select-selector){
   padding: 0 7px;
  }
  .steps {
    width: 80%;
    margin: 10px 10%;
  }

  .content {
    padding: 10px;

    .unit {
      line-height: 32px;
      padding: 6px 12px;
      background: #eaeaea;
    }

    .tag {
      border: 1px solid #ccc;
      padding: 4px 8px;
      margin-right: 0px;
    }
  }
}
.card-box {
  width: 200px;
  height: 140px;
  padding: 10px 30px;
  background-color: #f7f7f7;
  margin-right: 16px;
  border-radius: 12px;
  cursor: pointer;
  .card-upload {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    img {
      width: 100%;
      object-fit: contain;
    }
  }
}
.card-content {
  display: flex;
}
.card-img {
  width: 200px;
  height: 140px;
  border-radius: 12px;
  padding: 8px;
  background: #fafafa;
  margin-right: 16px;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  position: relative;
  .img {
    width: 100%;
    object-fit: contain;
    overflow: hidden;
    border-radius: 5px;
  }
  .mask {
    position: absolute;
    top: 0px;
    left: 0;
    width: 200px;
    height: 140px;
    border-radius: 12px;
    display: none;
    justify-content: center;
    align-items: center;
    background: rgba(0, 0, 0, 0.4);
    cursor: default;
    .icon {
      color: #fff;
      cursor: pointer;
      font-size: 16px;
    }
    -webkit-transition: all 0.5s;
    transition: all 0.5s;
  }

  &:hover {
    .mask {
      display: flex;
    }
  }
}
.font-gary {
  color: #999;
}
.tips {
  margin-top: 40px;
  background-color: #f5f7fa;
  line-height: 40px;
  padding: 0 10px;
  .tips-title {
    color: #636467;
  }
}

</style>
